package com.skyline.energy.provider.gwhalin;

import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.skyline.energy.cache.Cache;
import com.skyline.energy.cache.CacheErrorHandler;

public class MemcachedCache implements Cache {
	private final MemCachedClient client;
	
	public MemcachedCache(MemCachedClient client) {
		this.client = client;
	}
	
	@Override
	public void add(String key, Object value) {
		add(key, value, 0L);
	}

	@Override
	public void add(String key, Object value, long expiry) {
		if(value == null) { // can't set a null value to memcached
			return;
		}
		Date expireDate = new Date(expiry);;
		boolean ok = client.set(key, value, expireDate);
		if(!ok) {
			CacheErrorHandler.handleError(new Exception("add Object to memcache failed"));
		}
	}

	@Override
	public boolean delete(String key) {
		boolean ok = client.delete(key);
		if(!ok) {
			CacheErrorHandler.handleError(new Exception("delete Object in memcache failed"));
		}
		return ok;
	}

	@Override
	public void removeAll() {
		boolean ok = client.flushAll();
		if(!ok) {
			CacheErrorHandler.handleError(new Exception("flushAll Object in memcache failed"));
		}
	}

	@Override
	public Object get(String key) {
		return client.get(key);
	}

	@Override
	public boolean keyExists(String key) {
		return client.keyExists(key);
	}

}
